#!/usr/bin/env python
#coding=utf-8
# author:wade
# contact: 317909531@qq.com
# datetime:2021/2/27 14:47

"""
文件说明：
"""
import os

import jwt
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render
from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import APIException, AuthenticationFailed
from rest_framework.renderers import TemplateHTMLRenderer

from shareAPI2020TB import settings
from shareAPI2020TB.settings import BASE_DIR

"""
文件说明： 检查token的验证模块
"""




class JWT_YanZheng_1(BaseAuthentication): #权限认证
    def authenticate(self, request):
        print('-----jwt-Start 验证token')
        SALT = settings.SECRET_KEY
        # 获取token的值
        msg = None
        # 先判断头部有没有token，如果有，取出来token
        # 如果没有，查一下看看是否有请求字段里边的token，
        if 'token' in request.COOKIES:
            token  = request.COOKIES['token']
            tokenFrom = 'success'
        else:
            tokenFrom = "缺少token字段，cookie中没有token"
            # return HttpResponse("123")
            return (None, None)

        print(f"【请求类型】:{request.META.get('CONTENT_TYPE')} 【令牌token】:{token} 【获得方式】:{tokenFrom}")

        payload = None

        try:
            payload = jwt.decode(token, key=SALT, verify=True)
        except jwt.exceptions.ExpiredSignature:
            msg = f"token失效"
            raise AuthenticationFailed({'code': 403, 'msg': msg})
        except jwt.exceptions.DecodeError:
            msg = f"token认证失败"
            raise AuthenticationFailed({'code': 403, 'msg': msg})
        except jwt.exceptions.InvalidTokenError:
            msg = f"非法token"
            raise AuthenticationFailed({'code': 403, 'msg': msg})

        print(payload['user_id'], payload['username']) #这是token密令中隐藏的内容

        return (payload, token)